(function(angular) {
    "use strict";

    var ctl_module = angular.module("cloapCertificateApp.controller");

    ctl_module.controller("check_organ.listCtl", function($scope, $modal, CheckOrgan) {
        var modal_instance = null;

        $scope.widget_title = "审查机构";
        $scope.check_organs = CheckOrgan.query();

        $scope.editOrAdd = function(operate, check_organ_id) {
            var ctl = isAdd(operate) ? "check_organ.addCtl" : "check_organ.editCtl";

            modal_instance = $modal.open({
                scope: $scope,
                templateUrl: "/cloap/app/cloapCertificateApp/partials/check_organ_form.html",
                controller: ctl,
                resolve: {
                    params: function() {
                        return {
                            check_organ_id: check_organ_id
                        };
                    }
                }
            });

            function isAdd(operate) {
                return operate === "add";
            }
        };

        $scope.saveOrgan = function(save_method, data, callback) {
            CheckOrgan[save_method](data, callback, function() {
                alert("保存失败");
            });
        };

        $scope.toggleState = function(check_organ) {
            $scope.saveOrgan("toggle", check_organ, function toggleSuccess(response_organ) {
                check_organ.state = response_organ.state;
            });
        };

        $scope.closeModal = function() {
            modal_instance.close();
        };

    });

    ctl_module.controller("check_organ.editCtl", function($scope, CheckOrgan, params) {
        var save_method = "update";

        $scope.check_organ = CheckOrgan.get({manager_id: params.check_organ_id});
        $scope.widget_title = "编辑审查机构";

        $scope.save = function() {
            $scope.saveOrgan(save_method, $scope.check_organ, saveSuccessCallBack);
        };

        function saveSuccessCallBack(response_check_organ) {
            $scope.check_organs.splice(
                _.indexOf($scope.check_organs, $scope.check_organ), 1, response_check_organ
            );
            $scope.closeModal();
        }
    });

    ctl_module.controller("check_organ.addCtl", function($scope) {
        var save_method = "save";
        $scope.check_organ = {};
        $scope.widget_title = "添加审查机构";

        $scope.save = function() {
            $scope.saveOrgan(save_method, $scope.check_organ, saveSuccessCallBack);
        };

        function saveSuccessCallBack(response_check_organ) {
            $scope.check_organs.push(response_check_organ);
            $scope.closeModal();
        }

    });
}(angular));
